<?php
namespace app\store\controller\shop;
use app\store\controller\Controller;
use app\store\model\Article as ArticleModel;
use app\store\model\ArticleCategory as ArticleCategoryModel;
use app\store\model\Shop as ShopModel;

/**
 * 图文资讯控制器
 */
class Article extends Controller
{
	/**
     * 门店选择
     */
    public function opt()
    {
        if(!$this->is_admin OR $this->shop_mode == 10){
            $this->redirect('/'.url('shop.article/index',['shop_id' => $this->shop_id]));
        }
        $model = new ShopModel;
        $shoplist = $model->getList();
        return $this->fetch('opt', compact('shoplist'));
    }
    
    /**
     * 列表
     */
    public function index($shop_id)
    {
        $shop = ShopModel::detail($shop_id);
        $shop_name = $shop['shop_name'];
        $model = new ArticleModel;
        $list = $model->getList($shop_id);
        return $this->fetch('index', compact('list','shop_id','shop_name'));
    }

    /**
     * 添加
     */
    public function add($shop_id)
    {
        if (!$this->request->isAjax()) {
            // 分类
            $model = new ArticleCategoryModel;
            $category = $model->getList();
            return $this->fetch('add', compact('category'));
        }
        $model = new ArticleModel;
        if ($model->add($this->postData('article'),$shop_id)) {
            return $this->renderSuccess('添加成功', url('shop.article/index',['shop_id'=>$shop_id]));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 删除
     */
    public function delete($article_id)
    {
        $model = ArticleModel::detail($article_id);
        if ($model->remove()) {
           return $this->renderSuccess('删除成功'); 
        }
        $error = $model->getError() ?: '删除失败';
        return $this->renderError($error);
        
    }

    /**
     * 编辑
     */
    public function edit($article_id,$shop_id)
    {
        //详情
        $model = ArticleModel::detail($article_id);
        if (!$this->request->isAjax()) {
            //分类
            $ArticleCategory = new ArticleCategoryModel;
            $category = $ArticleCategory->getList();
            return $this->fetch('edit', compact('model', 'category'));
        }
        // 更新记录
        if ($model->edit($this->postData('article'))) {
            return $this->renderSuccess('更新成功', url('shop.article/index',['shop_id'=>$shop_id]));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }    
    
    /**
     * 状态切换
     */
    public function status($article_id)
    {
        $model = ArticleModel::detail($article_id);
        if($model->status()){
            return $this->renderSuccess('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
}
